package com.wutianyi.module.product.impl;

import java.util.Date;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Text;
import com.wutianyi.module.product.ProductInfoDao;
import com.wutianyi.module.product.dataobject.ProductInfoDO;
import com.wutianyi.utils.Utils;

import static com.wutianyi.entity.EntityTypeEnum.ProductInfo;
import static com.wutianyi.entity.DataStoreField.DS_P_VALUE;

public class ProductInfoDaoDataStoreImpl implements ProductInfoDao {
	
	private static DatastoreService datastoreService = DatastoreServiceFactory
			.getDatastoreService();
	
	private void setEntity(ProductInfoDO productInfo) {
		int id = 0 != productInfo.getId() ? productInfo.getId() : productInfo.getProductId();
		productInfo.setGmtCreate(new Date());
		Entity entity = new Entity(ProductInfo.name(), id);
		entity.setProperty(DS_P_VALUE, new Text(Utils.serialize(productInfo)));
		datastoreService.put(entity);
		productInfo.setId(id);
	}
	
	@Override
	public ProductInfoDO getProductInfoByProductId(int productId) {
		Query query = new Query(KeyFactory.createKey(ProductInfo.name(), productId));
		Entity entity = datastoreService.prepare(query).asSingleEntity();
		
		if (null != entity) {
			ProductInfoDO productInfo = (ProductInfoDO) Utils.unSerialize(entity
					.getProperty(DS_P_VALUE));
			productInfo.setId((int) entity.getKey().getId());
			return productInfo;
		}
		return null;
	}
	
	@Override
	public int createProductInfo(ProductInfoDO productInfo) {
		productInfo.setId(0);
		setEntity(productInfo);
		return 1;
	}
	
	@Override
	public int updateProductInfo(ProductInfoDO productInfo) {
		setEntity(productInfo);
		return 1;
	}
	
	@Override
	public int deleteProductInfo(int id) {
		datastoreService.delete(KeyFactory.createKey(ProductInfo.name(), id));
		return 1;
	}
	
}
